"""Make figure showing new novels by gender percentages.

When numbers are known, they are shown. When they are not known, model estimates
are shown.

"""
import argparse

import matplotlib.patches
import matplotlib.pyplot as plt
import matplotlib.style
import matplotlib.ticker

import make_table_novels_by_year  # function called likely belongs in datasets
import plot_common

parser = argparse.ArgumentParser()
parser.add_argument('output_filename', help='Output path for figure.')

# use seaborn style globally
matplotlib.style.use('seaborn-deep')


def make_plot(output_filename):
    df = make_table_novels_by_year.dataset_decades()
    fig = plt.figure()  # noqa
    ax = plt.gca()
    assert len(df) == 13, len(df)
    legend_handles = []

    known_pcts = {
        (1800, 'men'): 30,
        (1800, 'women'): 41,
        (1800, 'unknown'): 12,
        (1810, 'men'): 28,
        (1810, 'women'): 42,
        (1810, 'unknown'): 13,
        (1820, 'men'): 41,
        (1820, 'women'): 30,
        (1820, 'unknown'): 11,
    }
    for i, year in enumerate(df.index):
        if year in {1800, 1810, 1820}:
            # values are known for these decades
            for j, gender in enumerate(['men', 'women', 'unknown']):
                value = known_pcts[(year, gender)]
                color = plt.get_cmap('Dark2').colors[j]
                group_offset = -1.5 + j * 1.5
                ax.plot(year + group_offset, value, marker='.', alpha=0.7, color=color)
            continue
        for j, gender in enumerate(['men', 'women', 'unknown']):
            p05, p25, p75, p95 = df.loc[year, [f'y_{gender}_sim_pct_{p}' for p in ('p05', 'p25', 'p75', 'p95')]]
            width = plot_common.bar_width
            color = plt.get_cmap('Dark2').colors[j]
            group_offset = -1.5 + j * 1.5
            ax.fill_between([year - width / 8 + group_offset, year + width / 8 + group_offset], p05, p95, alpha=0.7, color=color)
            ax.fill_between([year - width / 2 + group_offset, year + width / 2 + group_offset], p25, p75, alpha=0.7, color=color)
            if i == 0:
                legend_handles.append(matplotlib.patches.Patch(color=color, label=f'{gender}-authored titles'))
            # markersize in pixels (?)
            # ax.plot(year, p50, marker='.', markersize=3, alpha=0.5, color='black')
    plt.legend(handles=legend_handles, loc='upper left')
    plt.ylim(0, 81.0)
    # title added in latex
    #plt.title('New Novels by Author Gender, 1790-1919')
    years, labels = list(df.index), [f'{year:d}s' for year in df.index]
    plt.xticks(years, labels, rotation=45)
    pos, _ = plt.yticks()
    plt.yticks(pos, [f'{int(y):d}%' for y in pos])
    plt.tight_layout()
    plt.savefig(output_filename)
    print('saved plot to file:', output_filename)


if __name__ == '__main__':
    args = parser.parse_args()
    make_plot(args.output_filename)
